package game;

import java.awt.Color;
import java.awt.Graphics;

public class VisibleBadGuy extends Thread implements VisibleCharacter {

	Graphics g;

	int x, y, width, height;

	Color color;

	Character c;

	VisibleMarine target;

	int i = 0;

	public VisibleBadGuy(Character c, Graphics g, int x, int y, Color color) {
		this.g = g;
		this.color = color;
		width = 50;
		height = 50;
		this.x = x;
		this.y = y;
		this.c = c;

		g.setColor(color);
		g.fillRect(x, y, width, height);

	}

	public void run() {

		int targetX, targetY;
		int diffX, diffY;
		int hyp;
		int newX, newY;

		// if (Math.abs(diffX) > Math.abs(diffY)){
		// newX = diffX / diffY-x;
		// newY = diffX / diffY;
		// }
		//		
		// else{
		// newX = diffY / diffX-y;
		// newY = diffY / diffX;
		// }
		while (true) {
			try {
				this.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			targetX = target.getX();
			targetY = target.getY();
			diffX = x - targetX;
			diffY = y - targetY;
			hyp = -(int) Math.sqrt((diffX * diffX) + (diffY * diffY));
			if (hyp != 0) {
				newX = 3 * diffX / hyp;
				newY = 3 * diffY / hyp;
			}
			else{
				newX = 0;
				newY = 0;
			}
			
			this.move(newX, newY);
		}

	}

	public void attaque(Character c) throws DeathException {
		c.attaque(c);
	}

	public int getHp() {
		return c.getHp();
	}

	public int getSpeed() {
		return c.getSpeed();
	}

	public void takeDammage(int dammage) throws DeathException {
		try {
			c.takeDammage(dammage);
		} catch (DeathException e) {
			this.stop();
			this.remove();
			throw(e);
		}
	}

	public void setTarget(VisibleMarine c) {
		target = c;
	}

	public void move(int x, int y) {
		int newX = this.x + x;
		int newY = this.y + y;
		Color tmpColor = g.getColor();

		g.setColor(color);
		g.clearRect(this.x, this.y, width, height);
		g.fillRect(this.x + x, this.y + y, width, height);
		g.setColor(tmpColor);

		this.x = newX;
		this.y = newY;
	}

	public void remove() {
		g.clearRect(this.x, this.y, width, height);
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	public int getWidth() {
		return width;
	}

	public void attaque(VisibleCharacter c) throws DeathException {
		c.takeDammage(this.c.getStrength());		
	}
}
